package com.assessment.util;

import cn.hutool.core.util.StrUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT工具类
 */
@Slf4j
public class JwtUtils {

    // 密钥
    private static final String SECRET = "assessment_secret_key_must_be_at_least_32_bytes_long";

    // 过期时间（毫秒）
    private static final long EXPIRE_TIME = 7 * 24 * 60 * 60 * 1000;

    // 根据密钥字符串生成密钥对象
    private static SecretKey getSecretKey() {
        return Keys.hmacShaKeyFor(SECRET.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * 生成令牌
     */
    public static String createToken(Integer userId, String username, String role) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userId);
        claims.put("username", username);
        claims.put("role", role);

        Date issuedAt = new Date();
        Date expiration = new Date(issuedAt.getTime() + EXPIRE_TIME);

        return Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(issuedAt)
                .setExpiration(expiration)
                .signWith(getSecretKey(), SignatureAlgorithm.HS256)
                .compact();
    }

    /**
     * 解析令牌
     */
    public static Claims parseToken(String token) {
        try {
            return Jwts.parserBuilder()
                    .setSigningKey(getSecretKey())
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            log.error("解析令牌失败", e);
            return null;
        }
    }

    /**
     * 获取用户ID
     */
    public static Integer getUserId(String token) {
        if (StrUtil.isBlank(token)) {
            return null;
        }

        Claims claims = parseToken(token);
        if (claims == null) {
            return null;
        }

        return claims.get("userId", Integer.class);
    }

    /**
     * 获取用户名
     */
    public static String getUsername(String token) {
        if (StrUtil.isBlank(token)) {
            return null;
        }

        Claims claims = parseToken(token);
        if (claims == null) {
            return null;
        }

        return claims.get("username", String.class);
    }

    /**
     * 获取角色
     */
    public static String getRole(String token) {
        if (StrUtil.isBlank(token)) {
            return null;
        }

        Claims claims = parseToken(token);
        if (claims == null) {
            return null;
        }

        return claims.get("role", String.class);
    }

    /**
     * 验证令牌是否过期
     */
    public static boolean isExpired(String token) {
        if (StrUtil.isBlank(token)) {
            return true;
        }

        Claims claims = parseToken(token);
        if (claims == null) {
            return true;
        }

        Date expiration = claims.getExpiration();
        return expiration.before(new Date());
    }
}
